﻿package com.ytplayer.screen
{
	import com.imageworks.debug.Debugger;
	import com.j4w.SimpleMask;
	import flash.display.DisplayObject;
	import flash.display.Sprite;
	import flash.display.Stage;
	import flash.events.Event;
	/**
	 * ...
	 * @author Jakub Wagner
	 */
	public class ScreenController
	{
		private static var _instance:ScreenController;
		
		private var _stage:Stage;
		private var _holder:Sprite = new Sprite();

		private var _currentScreen:Screen;
		private var _lastScreen:Screen;

		{
			_instance = new ScreenController();
		}

		public function ScreenController()
		{
			if (_instance) {
				Debugger.error ('You are not allowed to create new instance of ScreenController. To access ScreenController use ScreenController.getInstance()');
				throw new Error('You are not allowed to create new instance of ScreenController. To access ScreenController use ScreenController.getInstance()');
			}
		}

		/**
		 * @return vrací instanci ScreenController
		 */
		public static function getInstance():ScreenController
		{
			return _instance;
		}

		/**
		 * Zobrazí požadovaný screen. Právě zobrazený screen je shován a následně odstraněn.
		 * @param	_screen
		 */
		public function showScreen(_screen:Screen):void {
			if (!isInicialized()) {
				Debugger.error("ERROR: ScreenController is not initialized!");
				throw new Error("ERROR: ScreenController is not initialized!");
			}
			if (_lastScreen) {
				_lastScreen.hide();
			}
			_currentScreen = _screen;
			_currentScreen.setSize(_stage.stageWidth, _stage.stageHeight);
			_currentScreen.show();
			_holder.addChild(_currentScreen);

			_lastScreen = _currentScreen;
		}

		/**
		 * Připraví screen controller pro zadanou stage.
		 * @param	__stage  reference na stage
		 */
		public function init(__stage:Stage):void
		{
			_stage = __stage;
			_stage.addChild(_holder);
			_stage.addEventListener(Event.RESIZE, onStageResize);
		}

		/**
		 * Vrací, zda je ScreenController inicializován.
		 * @return true, pokud je inicializován
		 */
		public function isInicialized():Boolean
		{
			return _stage != null;
		}

		/**
		 * Vrací šířku stage.
		 */
		public function get stageWidth():Number
		{
			return _stage.stageWidth;
		}

		/**
		 * Vrací výšku stage.
		 */
		public function get stageHeight():Number
		{
			return _stage.stageHeight;
		}
		
		/**
		 * Maska holderu, obsahující screeny.
		 */
		public function get mask():DisplayObject 
		{
			return _holder.mask;
		}
		
		public function set mask(value:DisplayObject):void 
		{
			_holder.mask = value;
		}

		private function onStageResize(e:Event):void
		{
			if (_currentScreen){
				_currentScreen.setSize(stageWidth, stageHeight);
			}
		}

	}

}

